import { Toast } from 'vant';
import {SPLIT_BLANK} from "@/utils/enum";

export class Scanner {
    constructor(focusEl, showToast, execFn, minLength) {
        this.showToast = showToast;
        this.focusEl = focusEl;     //扫码焦点 防止扫码回车按到上一次的按钮 可为空值
        this.scanParams = {
            code: "",
            lastTime: "",
            nextTime: "",
            lastCode: "",
            nextCode: "",
        }
        this.execFn = execFn;       //外部传入方法, fn(e,scanner,callback)
        this.minLenght = minLength ? minLength : 5
    }

    /* 监听扫码 */
    watchScannerFn() {
        const that = this;
        that.removeScannerFn();
        if(that.showToast)  {
            Toast({
                type: "loading",
                message: "请扫码",
                forbidClick: true,
                duration: 5000,
            });
        }
        window.addEventListener("keydown", that.execFn);
    }

    /* 移除监听扫码 */
    removeScannerFn() {
        const that = this;
        window.removeEventListener("keydown", that.execFn);
        Object.keys(that.scanParams).forEach(key => {
            that.scanParams[key] = "";
        });
    }

    /* 执行扫码结果 */
    execScannerFn(e, that, fn) {
        if(that.focusEl) {
            that.focusEl.focus();
        }
        if(that.showToast)  {
            Toast.clear();
        }
        if (window.event) {
            // IE
            that.scanParams.nextCode = e.keyCode;
        } else if (e.which) {
            // Netscape/Firefox/Opera
            that.scanParams.nextCode = e.which;
        }
        if (e.which === 13) {
            if (that.scanParams.code.length < that.minLenght) return; // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有
            if(that.showToast)  {
                Toast.clear();
                Toast({
                    type: "loading",
                    message: "二维码解析中",
                    forbidClick: true,
                    duration: 20000
                });
            }
            let scanParam = that.scanParams.code.replace(/Shift/g, SPLIT_BLANK);

            //处理回调
            fn(scanParam);

            that.scanParams.code = "";
            that.scanParams.lastCode = "";
            that.scanParams.lastTime = "";
            return;
        }

        that.scanParams.nextTime = new Date().getTime();
        if (!that.scanParams.lastTime && !that.scanParams.lastCode) {
            that.scanParams.code += e.key;
        }
        if (that.scanParams.lastCode && that.scanParams.lastTime && (that.scanParams.nextTime - that.scanParams.lastTime > 500)) {
            // 当扫码前有keypress事件时,防止首字缺失
            that.scanParams.code = e.key;
        } else if (that.scanParams.lastCode && that.scanParams.lastTime) {
            that.scanParams.code += e.key;
        }
        that.scanParams.lastCode = that.scanParams.nextCode;
        that.scanParams.lastTime = that.scanParams.nextTime;
    }
}